package com.hmdp.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Long startTime = 1735689600L ;
    private static final Integer bitCounts = 32;
    /**
     * 生成唯一标识
     * @return
     */
    public Long GenerateAUniqueCode(String prefix){
        //生成当前时间
        LocalDateTime now = LocalDateTime.now();
        //当前时间转换为秒
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //时间戳：当前时间减去起始时间
        long timeStamp = nowSecond - startTime;
        //添加自增32位值
        String dateTime = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long increment = stringRedisTemplate.opsForValue().increment("increment:" + dateTime + ":" +prefix);
        //时间戳往前位移32位
        long timeAndRandom = timeStamp << bitCounts | increment;
        return timeAndRandom;
    }

//    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
//        long startTime = localDateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(startTime);
//    }

}
